﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DatabaseManager.Infrastructure.Configuration;
using DatabaseManager.Infrastructure.Connections;
using DatabaseManager.Utilities.CustomControls;
using DatabaseManager.WinForms.Services;

namespace DatabaseManager.WinForms.Pages
{
    public partial class ModelGenPage : XtraUcBasePage
    {
        private readonly ModelGenerationService _modelGenerationService;

        public ModelGenPage()
        {
            InitializeComponent();

            // 初始化依赖链
            IConfigurationProvider configProvider = new AppSettingsConfigurationProvider();
            IDatabaseConnectionFactory connectionFactory = new DatabaseConnectionFactory(configProvider.GetSystemConnectionString());
            var dbConnectionService = new DbConnectionService(configProvider, connectionFactory);

            // 初始化模型生成服务
            _modelGenerationService = new ModelGenerationService(dbConnectionService);
        }

        public void Init()
        { 
        
        }
        private void btnGenModels_Click(object sender, EventArgs e)
        {
            this.ModelGeneratioin();
        }

        private void ModelGeneratioin()
        {
            // 1. 禁用按钮，防止重复点击
            btnGenModels.Enabled = false;
            progressBar1.Value = 0;


            lblProgress.Text = "准备生成...";

            // 2. 配置生成参数（可通过界面输入框让用户指定）
            //string outputDir = @"D:\Projects\YourApp\Models"; // 输出目录
            //string outNamespace = "YourApp.Models"; // 实体类命名空间

            var (outNamespace, outputDir) = ModelGenerationHelper.ProcessNamespaceAndOutputDir(
                this.txtNamespace.Text.Trim(),
                this.txtOutputDir.Text.Trim(),
                @"D:\Temp"); // 可选：指定默认基础目录

            // 3. 初始化进度报告（自动切换到 UI 线程）
            var progress = new Progress<int>(value =>
            {
                // 更新进度条
                progressBar1.Value = value;

                // 更新进度文本
                lblProgress.Text = value < 100
                ? $"正在生成... {value}%"
                : "生成完成，正在清理...";
            });

            // 4. 后台执行生成任务（避免 UI 卡顿）
            Task.Run(() =>
            {
                try
                {
                    // 调用生成方法，传入进度回调
                    var result = _modelGenerationService.GenerateModels(outputDir, outNamespace, progress);

                    // 生成完成后在 UI 线程显示结果
                    this.Invoke((Action)(() =>
                    {
                        // 清理 C#8.0 语法（如果需要）
                        if (result.IsSuccess && "FW".Equals(rgYfType.EditValue?.ToString()))
                        {
                            ModelGenerationHelper.CleanNullableSyntax(outputDir);
                        }

                        // 显示结果
                        if (result.IsSuccess)
                        {
                            MessageBox.Show(result.Message, "生成成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            System.Diagnostics.Process.Start("explorer.exe", outputDir);
                        }
                        else
                        {
                            MessageBox.Show(result.Message, "生成失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {result.Message}";
                            System.Diagnostics.Trace.WriteLine(logMessage);
                        }

                        // 重置进度控件
                        progressBar1.Value = 0;


                        lblProgress.Text = "就绪";
                        // 恢复按钮可用
                        btnGenModels.Enabled = true;
                    }));
                }
                catch (Exception ex)
                {
                    this.Invoke((Action)(() =>
                    {
                        MessageBox.Show($"执行失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        progressBar1.Value = 0;


                        lblProgress.Text = "就绪";
                        btnGenModels.Enabled = true;
                    }));
                }
            });
        }
    }
}
